﻿using ArivisTests.Models;
using System.Data.Entity;
using System.Web.Security;
using WebMatrix.WebData;

namespace ArivisTests
{
    public static class AuthConfig
    {
        public static void RegisterAuth()
        {
            Database.SetInitializer<ArivisTestsDBContext>(null);
            using (var context = new ArivisTestsDBContext())
            {
                if (!context.Database.Exists())
                {
                    // Create the SimpleMembership database without Entity Framework migration schema
                    context.Database.CreateIfNotExists();
                }
            }

            WebSecurity.InitializeDatabaseConnection("DefaultConnection", "UserProfile", "UserId", "UserName", autoCreateTables: true);

            // create all required roles
            foreach (string role in KnownRoles.GetRequired())
            {
                if (!Roles.RoleExists(role))
                {
                    Roles.CreateRole(role);
                }
            }

            // make sure there is at least one 'Admin'-User
            if (Roles.GetUsersInRole("Admin").Length == 0)
            {
                // Create 'Admin'-User
                if (!WebSecurity.UserExists("Admin"))
                {
                    WebSecurity.CreateUserAndAccount("Admin", "Admin", requireConfirmationToken: false);
                }
                // Assign 'Admin'-User to 'Admin'-Group
                Roles.AddUserToRole("Admin", "Admin");
            }
        }
    }
}
